%%
%% Copyright (c) 2013-2017 EMQ Enterprise Inc.
%%

-module(emq_mod_subscription).

-author("Feng Lee <feng@emqtt.io>").

-behaviour(emqttd_gen_mod).

-include_lib("emqttd/include/emqttd.hrl").

-include_lib("emqttd/include/emqttd_protocol.hrl").

-export([load/1, on_client_connected/3, unload/1]).

-define(TAB, ?MODULE).

%%--------------------------------------------------------------------
%% Load/Unload Hook
%%--------------------------------------------------------------------

load(Topics) ->
    emqttd:hook('client.connected', fun ?MODULE:on_client_connected/3, [Topics]).

on_client_connected(?CONNACK_ACCEPT, Client = #mqtt_client{client_id  = ClientId,
                                                           client_pid = ClientPid,
                                                           username   = _Username}, _Topics) ->
    %% select topic
%%    {ok, C} = eredis:start_link("192.168.1.145", 6379, 0, "redis"),
    {ok, C} = eredis:start_link("139.224.57.152", 6379, 0, "7fcb6fd7be367b92a351b29504183750"),
    Value = eredis:q(C, ["HEXISTS", "topic", ClientId]),
    GetTopic = case Value of
        {ok,<<"1">>} ->
            eredis:q(C, ["HGET", "topic", ClientId]);
        {ok,<<"0">>} ->
            {ok, not_create};
        _ ->
            {ok, not_exist}
    end,
    %% JSON to erlang term
    %% 判断GetTopic是否存在
    case GetTopic of
        {ok, not_create} ->
            io:format("topic is not create. ~n");
        {ok, not_exist} ->
            io:format("topic is not exist. ~n");
        _ ->
            io:format("GetTopic:~p~n", [GetTopic]),
            DecodeTopic = jsx:decode(lists:nth(2, (tuple_to_list(GetTopic)))),
            io:format("DecodeTopic:~p~n", [DecodeTopic]),
            SubTopic = lists:nth(2, tuple_to_list(lists:nth(1, DecodeTopic))),
            io:format("SubTopic:~p~n", [SubTopic]),
            SubQos = lists:nth(2,tuple_to_list(lists:nth(2, DecodeTopic))),
            io:format("SubQos:~p~n", [SubQos]),
            %% judge client subscribe many topics
            %% Todo 去重
            ManyTopic = is_list(SubTopic),
            io:format("ManyTopics:~p~n", [ManyTopic]),
            TopicTable = case ManyTopic of
                             false ->
                                 [{SubTopic, SubQos}];
                             true ->
                                 lists:zip(SubTopic, SubQos);
                             _ ->
                                 io:format("TopicTable is not exist. ~n")
                         end,
            io:format("TopicTable:~p~n", [TopicTable]),

%%    Replace = fun(Topic) -> rep(<<"%u">>, Username, rep(<<"%c">>, ClientId, Topic)) end,
%%    TopicTable = [{Replace(Topic), Qos} || {Topic, Qos} <- Topics],
            ClientPid ! {subscribe, TopicTable}
    end,
    {ok, Client};

on_client_connected(_ConnAck, _Client, _State) ->
    ok.

unload(_) ->
    emqttd:unhook('client.connected', fun ?MODULE:on_client_connected/3).

%%--------------------------------------------------------------------
%% Internal Functions
%%--------------------------------------------------------------------

rep(<<"%c">>, ClientId, Topic) ->
    emqttd_topic:feed_var(<<"%c">>, ClientId, Topic);
rep(<<"%u">>, undefined, Topic) ->
    Topic;
rep(<<"%u">>, Username, Topic) ->
    emqttd_topic:feed_var(<<"%u">>, Username, Topic).

